package com.company.controller;

import com.company.controller.result.Codes;
import com.company.controller.result.Results;
import com.company.pojo.User;
import com.company.service.UserService;
import com.company.system.exception.BusinessException;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author
 * @date 2021-07-26 11:38
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @GetMapping("/{uuid}")
    public Results get(@PathVariable("uuid") Integer id){
        User user = userService.get(id);
        if (id == 10){
            throw new BusinessException("查询错误", Codes.GET_ERROR);
        }
        return  new Results(null != user ? Codes.DELETE_OK:Codes.GET_ERROR,user,"操作成功");
    }

    @PostMapping
    public Results save(User user){
        boolean flag = userService.save(user);
        return new Results(flag ? Codes.SAVE_OK: Codes.SAVE_ERROR);
    }

    @PutMapping
    public Results update(User user){
        boolean flag = userService.update(user);
        return new Results(flag ? Codes.UPDATE_OK: Codes.UPDATE_ERROR);
    }

    @DeleteMapping("/{uuid}")
    public Results delete(@PathVariable Integer uuid){
        boolean flag = userService.delete(uuid);
        return new Results(flag ? Codes.DELETE_OK: Codes.DELETE_ERROR);
    }



    @GetMapping("/{page}/{size}")
    public Results getAll(@PathVariable Integer page, @PathVariable Integer size){
        PageInfo<User> all = userService.getAll(page, size);
        return new Results(null != all ? Codes.GET_OK: Codes.GET_ERROR,all);
    }

    @PostMapping("/login")
    public Results login(String userName, String password){
        User user = userService.login(userName,password);
        return new Results(null != user ? Codes.GET_OK: Codes.GET_ERROR,user);
    }

}
